package home;

import games.CupMatch;

import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import operations.HibernateManager;

import org.hibernate.Criteria;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import teams.Team;

public class CupMatchHome {

    public List<CupMatch> getCupMatchesPlayedBy(final Team team) {
        Session session = HibernateManager.instance().getSession();
        Criteria criteria = session.createCriteria(CupMatch.class);
        criteria.add(Restrictions.or(Restrictions.eq("team1", team), Restrictions.eq("team2", team)));
        criteria.createCriteria("simpleMatch1");
        criteria.createCriteria("simpleMatch2");
        return criteria.list();

    }

    private int getTeamVictories(final Team team, final List<CupMatch> teamCupMatches) {
        int victories = 0;

        for (CupMatch cupMatch : teamCupMatches) {
            if (cupMatch.getWinner() == team) {
                victories++;
            }
        }

        return victories;
    }

    public class TeamAndVictories implements Comparable<TeamAndVictories> {

        @SuppressWarnings("unused")
        private Team team;

        private int victories;

        private TeamAndVictories(final Team team, final int victories) {
            super();
            this.team = team;
            this.victories = victories;
        }

        @Override
        public int compareTo(final TeamAndVictories anotherTeamAndVictories) {

            return Integer.valueOf(anotherTeamAndVictories.victories).compareTo(Integer.valueOf(this.victories));
        }

        @Override
        public String toString() {
            return this.team + "(" + this.victories + ")" + System.getProperty("line.separator");
        }

    }

    public SortedSet<TeamAndVictories> getTeamsAndCupMatches() {
        Session session = HibernateManager.instance().getSession();
        Criteria criteria = session.createCriteria(CupMatch.class);
        criteria.createCriteria("simpleMatch1");
        criteria.createCriteria("simpleMatch2");
        criteria.createCriteria("team1");
        criteria.setCacheable(true);

        List<CupMatch> partidosDeCopa = criteria.list();
        List<Team> teams = criteria.setProjection(Projections.groupProperty("team1").as("teamName")).list();

        SortedSet<TeamAndVictories> result = new TreeSet<TeamAndVictories>();
        for (Team team : teams) {
            TeamAndVictories teamWrapped = new TeamAndVictories(team, this.getTeamVictories(team, partidosDeCopa));
            result.add(teamWrapped);
        }

        return result;
    }
}
